package cron

import (
	"github.com/gofiber/fiber/v2"
	"github.com/robfig/cron/v3"
	"guns-excel/internal/app/model"
	"guns-excel/internal/app/service"
)

var Cron *cron.Cron

// 定时任务集合
var Crons = make(map[string]func())

func NewCron() {
	initTask()
	Cron = cron.New(cron.WithSeconds())
	Cron.Start()
	tasks, err := initJob()
	if err != nil {
		return
	}
	AddCron(tasks)
}

// 新增任务
func AddCron(tasks []*model.TimedTask) {
	for _, task := range tasks {
		// 动态添加定时任务
		id, err := Cron.AddFunc(task.JobCron, Crons[task.FuncName])
		if err != nil {
			return
		}
		m := new(model.TimedTask)
		m.JobId = id
		m.FuncName = task.FuncName
		m.IsStart = 1
		// 更新任务的jobId
		if err = service.TimedUpdate(&fiber.Ctx{}, m); err != nil {
			continue
		}
	}
}
